package com.heima.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.vo.ApUserVO;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        if (StrUtil.isBlank(dto.getPassword()) && StrUtil.isBlank(dto.getPhone())){
            //游客登录 基于0生成jwt令牌
            String token = AppJwtUtil.getToken(0L);
            return ResponseResult.okResult(token);
        }else {
            //非游客登录
            //1.查询用户是否存在
            ApUser one = lambdaQuery().eq(ApUser::getPhone, dto.getPhone()).one();
            if (one == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            //2.校验密码
            String password = one.getPassword();
            //将dto的密码进行加密然后与数据库密码进行比较
            boolean checkpw = BCrypt.checkpw(dto.getPassword(), password);
            if (!checkpw){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }else {
                //3.生成jwt令牌
                String token = AppJwtUtil.getToken(Long.valueOf(one.getId()));
                Map<String,Object> map = new HashMap<>();
                ApUserVO userVO = ApUserVO.builder()
                        .phone(one.getPhone())
                        .name(one.getName())
                        .id(one.getId())
                        .build();
                map.put("token",token);
                map.put("user",userVO);
                return ResponseResult.okResult(map);
            }
        }
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
//eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAACWL0QrDIAwA_yXPFUwaZ9q_UafMQUGIhY2xf1_K3u447gPP2WEHjyQ-0OZIkBw3bk74Vl0rpUSUTEIZFuhpwo4xoF9XDnEBPbPd-tZZj6urmj5qP5JZOu9maQzj-hr_E3GT6-zW-PsDg3nPeYAAAAA
//        .scsWY8v2ZCkU07FDBfjxqZAeTCJsL3sponyshuaJELjVuGEdjebJwJc7Pljjjl1URFC3dxCpWEkZ4pu6eNSmWw